/// <reference path="lib.js" />

(function () {

    var settlerHostUrlPattern = "http://www.thesettlersonline.ru/ru/play";
    var settlersAppServerUrlPattern = /http\:\/\/w\d\dg\d\d\.thesettlersonline\.ru\/GameServer\d\d\/amf/;

    var saServerUrl = "http://localhost:9999/Trade";
    var saRootUrl = "http://localhost:9999/EntryPoint/Index";

    var saDesiredWidth = 400;

    function saWindowLoaded(win, doc) {
        try {
            var container = doc.createElement("div");
            doc.body.appendChild(container);
            
            var link = doc.createElement("a");
            link.innerHTML = "[open]";
            link.href = saServerUrl;
            link.target = saServerUrl;
            link.setAttribute("style", "color: #008800; background-color: #000000; height: 25px; left: 0; position: absolute; top: 0; width: 50px;z-index: 100; font-weight:bold;");
            doc.body.appendChild(link);

            var iFrame = doc.createElement("iframe");
            iFrame.setAttribute("src", saRootUrl);
            container.appendChild(iFrame);

            var latestRequestData = null;

            SettlersAuto.DataReceiver.onReceiveResponse.addHandler(function (e) {
                if (settlersAppServerUrlPattern.test(e.url)) {
                    latestRequestData = e;
                }
            });

            function pageEventListener(evt) {
                try {
                    if (latestRequestData) {
                        evt.target.setAttribute("hasData", true);
                        evt.target.setAttribute("url", latestRequestData.url);
                        evt.target.setAttribute("statusCode", latestRequestData.statusCode);
                        evt.target.setAttribute("data", latestRequestData.data);
                    }
                    else {
                        evt.target.setAttribute("hasData", false);
                    }
                }
                catch (e) { alert(e); }

                latestRequestData = null;
            }

            document.addEventListener("saGetLastRequestDataEvent", function (e) { pageEventListener(e); }, false, true);
        }
        catch (ex) {
            alert(ex);
        }
    }

    SettlersAuto.onPageLoaded.addHandler(function(win){
        if (win && win.document.location == settlerHostUrlPattern) {
            saWindowLoaded(win, win.document);
        }
    });
})();

